package cn.hdu.liang.ch3;

import cn.hdu.liang.ch1.Apple;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;

import static java.util.Comparator.comparing;

class AppleComparator implements Comparator<Apple> {
    public int compare(Apple a1, Apple a2){
        return a1.getWeight().compareTo(a2.getWeight());
    }
}

public class Sorting {

    public static void main(String[] args){

        List<Apple> inventory = new ArrayList<>();
        inventory.addAll(Arrays.asList(new Apple(80,"green"), new Apple(155, "green"), new Apple(120, "red")));


        //第一种方式，实现接口
        inventory.sort(new AppleComparator());
        System.out.println("第一种方式，实现接口");
        System.out.println(inventory);

        //打乱
        inventory.set(1, new Apple(30, "green"));
        
        //第二种方式，匿名内部类
        inventory.sort(new Comparator<Apple>() {
            public int compare(Apple a1, Apple a2){
                return a1.getWeight().compareTo(a2.getWeight()); 
        }});
        System.out.println("第二种方式，匿名内部类");
        System.out.println(inventory);

        //打乱
        inventory.set(1, new Apple(20, "red"));
        
        //第三种方式，lambda表达式
        inventory.sort((a1, a2) -> a1.getWeight().compareTo(a2.getWeight()));
        System.out.println("第三种方式，lambda表达式");
        System.out.println(inventory);
        
        //打乱
        inventory.set(1, new Apple(10, "red"));
        
        //第四种方式，方法引用
        inventory.sort(comparing(Apple::getWeight));
        System.out.println("第四种方式，方法引用");
        System.out.println(inventory);


        inventory.sort(comparing(Apple::getWeight).reversed());
        System.out.println("逆序排列");
        System.out.println(inventory);

        inventory.sort(comparing(Apple::getWeight).thenComparing(Apple::getColor));
        System.out.println("比较器链");
        System.out.println(inventory);

    }

}
